package com.labtalk.admin.utils;

import com.labtalk.admin.pojo.model.BarcodeModel;

import java.util.Calendar;

public class BarcodeUtil {

    public static String getBarcode(BarcodeModel model) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(model.getValidity());
        String year = String.valueOf(calendar.get(Calendar.YEAR) - 2020);
        String week = String.valueOf(calendar.get(Calendar.WEEK_OF_YEAR));
        String spec = model.getSpec(); // 瓶规格
        String type = model.getType(); // 试剂类型
        String batchNo = StringUtil.toString(model.getBatchNo(), 3); // 批号
        String serialNo = StringUtil.toString(model.getSerialNo(), 4); // 序号
        String itemNo = StringUtil.toString(model.getItemNo(), 5); // 试剂瓶号

        // 正序拼接：试剂瓶号5 + 瓶规格1 + 试剂类型1 + 有效期年1 + 有效期周2 + 批号3 + 序号4
        String str = itemNo + spec + type + year + week + batchNo + serialNo;

        // 校验码算法
        StringBuilder sb = new StringBuilder(str);
        String reversedStr = sb.reverse().toString(); // 倒序
        int A = 0;
        int B = 0;
        int C;
        int[] numbers = new int[reversedStr.length()];
        for (int i = 0; i < reversedStr.length(); i++) {
            numbers[i] = reversedStr.charAt(i) - '0';  // 减去'0'的ASCII码值来得到真正的整数数值
        }
        for (int i = 1; i < numbers.length; i++) {
            if(i%2 == 1) {
                A = A + i; // 第二位开始偶数之和
            } else {
                B = B + i; // 第三位开始奇数之和
            }
        }
        A = A*3;
        C = A + B;
        String checkNo = String.valueOf(10 - C%10); // 校验码

        return str + checkNo;
    }
}
